import 'package:stacked/stacked.dart';
import '../heartbeat/blueprint/dynamic_model.dart';

/// 动态发布者
class ContentBroadcaster extends BaseViewModel {
  // 动态列表（模拟数据库）
  final List<ContentModel> _dynamics = [];

  // 动态评论列表
  final List<ContentCommentModel> _comments = [];

  // 动态点赞列表
  final List<ContentLikeModel> _likes = [];

  /// 获取所有动态
  List<ContentModel> get dynamics => List.from(_dynamics);

  /// 获取所有评论
  List<ContentCommentModel> get comments => List.from(_comments);

  /// 获取所有点赞
  List<ContentLikeModel> get likes => List.from(_likes);

  /// 初始化默认动态数据
  void populateDefaultContent() {
    _dynamics.clear();
    _dynamics.addAll(_generateDefaultContent());
    _populateDefaultComments();
    _populateDefaultLikes();
  }

  /// 获取默认动态数据
  List<ContentModel> _generateDefaultContent() {
    return [
      // 图片动态
      ContentModel(
        id: '1',
        userId: '1',
        title: 'Your unforgettable moments on game day',
        content:
            'Race day is always filled with challenges, excitement, and moving moments. What are some of the most unforgettable moments in your memory? Is it the joy of crossing the finish line? Or the cheers of the spectators along the way? Share these heartwarming stories and let\'s revisit the unique charm of the marathon together!',
        type: ContentType.image,
        imagePath: 'treasure_chest/images/dynamic1.png',
        createdAt: DateTime.now().subtract(const Duration(hours: 2)),
        likeCount: 24,
        commentCount: 5,
      ),
      ContentModel(
        id: '2',
        userId: '2',
        title: 'How to break personal records in competitions?',
        content:
            'Breaking a personal best (PB) is a proud moment for every runner! Come share your race strategies, training insights, or share some advice for struggling novice runners. Let your PB become more than just a dream, it\'s an achievable goal!',
        type: ContentType.image,
        imagePath: 'treasure_chest/images/dynamic2.png',
        createdAt: DateTime.now().subtract(const Duration(hours: 5)),
        likeCount: 42,
        commentCount: 6,
      ),
      ContentModel(
        id: '3',
        userId: '3',
        title: 'Which is the most beautiful track you have ever run on?',
        content:
            'Some races aren\'t just about racing; they\'re about visual and spiritual enjoyment! Share your "most beautiful" marathon course: city streets under a blue sky, romantic coastline scenery, or forest trails covered in spring blossoms and autumn leaves? Share them with fellow runners and find inspiration for your next run!',
        type: ContentType.image,
        imagePath: 'treasure_chest/images/dynamic3.png',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
        likeCount: 18,
        commentCount: 5,
      ),
      ContentModel(
        id: '4',
        userId: '4',
        title: 'What kind of running shoes do you need?',
        content:
            'Running shoes are every marathon runner\'s soulmate! Do you prefer cushioning, lightweight, or racing shoes? What brands and styles are your top choices? Share your running shoe experiences and why you chose them!',
        type: ContentType.image,
        imagePath: 'treasure_chest/images/dynamic4.png',
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 3)),
        likeCount: 31,
        commentCount: 6,
      ),
      ContentModel(
        id: '5',
        userId: '1',
        title: 'Recording the running people.',
        content:
            'Whether you\'re capturing a panoramic view of the track with a drone or capturing the expressions and movements of a sprint, every frame tells a story. Upload your photos, videos, or clips to show us the power and visual appeal of running!',
        type: ContentType.image,
        imagePath: 'treasure_chest/images/dynamic5.png',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
        likeCount: 27,
        commentCount: 5,
      ),
      ContentModel(
        id: '6',
        userId: '6',
        title: 'Run to create a sense of ritual for yourself!',
        content:
            'Every challenge is worth celebrating! Do you reward yourself with a new pair of shoes after hitting your PB? Or do you grab your medal and have a drink with your running buddies? Sharing your running ritual can help others realize that hard work and passion are worth cherishing!',
        type: ContentType.image,
        imagePath: 'treasure_chest/images/dynamic6.png',
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 6)),
        likeCount: 35,
        commentCount: 6,
      ),
    ];
  }

  /// 初始化默认评论数据
  void _populateDefaultComments() {
    _comments.clear();
    _comments.addAll(_generateDefaultComments());
  }

  /// 获取默认评论数据
  List<ContentCommentModel> _generateDefaultComments() {
    return [
      // 动态1的评论 - "Your unforgettable moments on game day" (5条评论)
      ContentCommentModel(
        id: '1',
        dynamicId: '1',
        userId: '2',
        content:
            'Crossing the finish line of my first marathon was absolutely magical! The crowd cheering and the sense of accomplishment was indescribable! 🏃‍♀️',
        createdAt: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '2',
        dynamicId: '1',
        userId: '3',
        content:
            'I remember the moment I saw my family at mile 20 - their support gave me the strength to push through the last 6 miles!',
        createdAt: DateTime.now().subtract(const Duration(hours: 1)),
      ),
      ContentCommentModel(
        id: '3',
        dynamicId: '1',
        userId: '4',
        content:
            'The sunrise during my early morning race was breathtaking! Nature\'s beauty made every step worth it.',
        createdAt: DateTime.now().subtract(const Duration(minutes: 45)),
      ),
      ContentCommentModel(
        id: '4',
        dynamicId: '1',
        userId: '5',
        content:
            'When I hit the wall at mile 18, a stranger\'s encouraging words kept me going. The running community is amazing!',
        createdAt: DateTime.now().subtract(const Duration(minutes: 30)),
      ),
      ContentCommentModel(
        id: '5',
        dynamicId: '1',
        userId: '6',
        content:
            'The medal ceremony was so emotional! All those months of training finally paid off. What a journey!',
        createdAt: DateTime.now().subtract(const Duration(minutes: 15)),
      ),

      // 动态2的评论 - "How to break personal records in competitions?" (6条评论)
      ContentCommentModel(
        id: '6',
        dynamicId: '2',
        userId: '1',
        content:
            'Consistent training and proper pacing are key! I broke my PB by focusing on negative splits.',
        createdAt: DateTime.now().subtract(const Duration(hours: 4)),
      ),
      ContentCommentModel(
        id: '7',
        dynamicId: '2',
        userId: '3',
        content:
            'Nutrition and hydration strategy made a huge difference for me. Fueling properly during long runs is crucial!',
        createdAt: DateTime.now().subtract(
          const Duration(hours: 3, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '8',
        dynamicId: '2',
        userId: '4',
        content:
            'Mental preparation is just as important as physical training. Visualization techniques really helped me!',
        createdAt: DateTime.now().subtract(const Duration(hours: 3)),
      ),
      ContentCommentModel(
        id: '9',
        dynamicId: '2',
        userId: '5',
        content:
            'Track workouts and tempo runs were game-changers for me. Speed work builds confidence!',
        createdAt: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '10',
        dynamicId: '2',
        userId: '6',
        content:
            'Recovery is crucial! I improved my times significantly when I started taking rest days seriously.',
        createdAt: DateTime.now().subtract(const Duration(hours: 2)),
      ),
      ContentCommentModel(
        id: '11',
        dynamicId: '2',
        userId: '7',
        content:
            'Running with a group or finding a training partner really helped me stay motivated and push harder!',
        createdAt: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 30),
        ),
      ),

      // 动态3的评论 - "Which is the most beautiful track you have ever run on?" (5条评论)
      ContentCommentModel(
        id: '12',
        dynamicId: '3',
        userId: '1',
        content:
            'The Boston Marathon course is absolutely stunning! Running through the historic towns was incredible.',
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 2)),
      ),
      ContentCommentModel(
        id: '13',
        dynamicId: '3',
        userId: '2',
        content:
            'I ran the Big Sur Marathon and the coastal views were breathtaking! The ocean on one side, mountains on the other.',
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 1)),
      ),
      ContentCommentModel(
        id: '14',
        dynamicId: '3',
        userId: '4',
        content:
            'The Cherry Blossom 10-Miler in DC was magical! Running under pink petals was like a dream.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, minutes: 45),
        ),
      ),
      ContentCommentModel(
        id: '15',
        dynamicId: '3',
        userId: '5',
        content:
            'The Paris Marathon course is beautiful! Running past the Eiffel Tower and along the Seine was unforgettable.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '16',
        dynamicId: '3',
        userId: '6',
        content:
            'The Great Wall Marathon in China was challenging but the views were absolutely spectacular!',
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, minutes: 15),
        ),
      ),

      // 动态4的评论 - "What kind of running shoes do you need?" (6条评论)
      ContentCommentModel(
        id: '17',
        dynamicId: '4',
        userId: '1',
        content:
            'I swear by Nike Air Zoom Pegasus for long runs! Great cushioning and durability.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, hours: 2, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '18',
        dynamicId: '4',
        userId: '2',
        content:
            'Brooks Ghost series has been my go-to for years. Perfect balance of comfort and responsiveness!',
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 2)),
      ),
      ContentCommentModel(
        id: '19',
        dynamicId: '4',
        userId: '3',
        content:
            'For racing, I love the Adidas Adios Pro 3. Super lightweight and fast!',
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, hours: 1, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '20',
        dynamicId: '4',
        userId: '5',
        content:
            'ASICS Gel-Nimbus for maximum cushioning! My feet thank me after long training runs.',
        createdAt: DateTime.now().subtract(const Duration(days: 1, hours: 1)),
      ),
      ContentCommentModel(
        id: '21',
        dynamicId: '4',
        userId: '6',
        content:
            'Hoka One One Clifton series is amazing for high mileage! The cushioning is incredible.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, minutes: 45),
        ),
      ),
      ContentCommentModel(
        id: '22',
        dynamicId: '4',
        userId: '7',
        content:
            'Saucony Triumph for the win! Great for both training and racing, very versatile.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 1, minutes: 30),
        ),
      ),

      // 动态5的评论 - "Recording the running people." (5条评论)
      ContentCommentModel(
        id: '23',
        dynamicId: '5',
        userId: '1',
        content:
            'Love the drone shots! The aerial view of runners on the course is so cinematic!',
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 1)),
      ),
      ContentCommentModel(
        id: '24',
        dynamicId: '5',
        userId: '2',
        content:
            'The slow-motion finish line captures are incredible! You can see every emotion.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 2, minutes: 45),
        ),
      ),
      ContentCommentModel(
        id: '25',
        dynamicId: '5',
        userId: '3',
        content:
            'I love how you capture the determination in people\'s faces during the tough miles!',
        createdAt: DateTime.now().subtract(
          const Duration(days: 2, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '26',
        dynamicId: '5',
        userId: '4',
        content:
            'The group running shots show the community spirit so well! Running brings people together.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 2, minutes: 15),
        ),
      ),
      ContentCommentModel(
        id: '27',
        dynamicId: '5',
        userId: '6',
        content:
            'Your photography really tells the story of the race! Every picture has emotion and energy.',
        createdAt: DateTime.now().subtract(const Duration(days: 2, minutes: 5)),
      ),

      // 动态6的评论 - "Run to create a sense of ritual for yourself!" (6条评论)
      ContentCommentModel(
        id: '28',
        dynamicId: '6',
        userId: '1',
        content:
            'I always treat myself to a new running outfit after a big race! It\'s my reward ritual.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 2, hours: 5, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '29',
        dynamicId: '6',
        userId: '2',
        content:
            'Post-race brunch with my running group is the best! We celebrate every finish together.',
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 5)),
      ),
      ContentCommentModel(
        id: '30',
        dynamicId: '6',
        userId: '3',
        content:
            'I frame my race bibs and hang them on my wall! Each one tells a story of my journey.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 2, hours: 4, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '31',
        dynamicId: '6',
        userId: '4',
        content:
            'Massage and stretching session after every long run - self-care is part of the ritual!',
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 4)),
      ),
      ContentCommentModel(
        id: '32',
        dynamicId: '6',
        userId: '5',
        content:
            'I write in my running journal after each race, reflecting on the experience and lessons learned.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 2, hours: 3, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '33',
        dynamicId: '6',
        userId: '7',
        content:
            'Sharing my race photos and story on social media helps me celebrate and inspire others!',
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 3)),
      ),

      // 动态7的评论 - "Check out my marathon training session!" (6条评论)
      ContentCommentModel(
        id: '34',
        dynamicId: '7',
        userId: '1',
        content:
            'That finish line sprint was incredible! Your form looks really good throughout the entire run.',
        createdAt: DateTime.now().subtract(const Duration(days: 3, hours: 2)),
      ),
      ContentCommentModel(
        id: '35',
        dynamicId: '7',
        userId: '2',
        content:
            'The rhythm you maintained for 15km is impressive! What\'s your training schedule like?',
        createdAt: DateTime.now().subtract(
          const Duration(days: 3, hours: 1, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '36',
        dynamicId: '7',
        userId: '3',
        content:
            'Your pacing strategy looks perfect! How do you stay so consistent over long distances?',
        createdAt: DateTime.now().subtract(const Duration(days: 3, hours: 1)),
      ),
      ContentCommentModel(
        id: '37',
        dynamicId: '7',
        userId: '4',
        content:
            'The training route looks beautiful! Running in nature must be so motivating.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 3, minutes: 45),
        ),
      ),
      ContentCommentModel(
        id: '38',
        dynamicId: '7',
        userId: '5',
        content:
            'Your breathing technique looks really controlled! Any tips for maintaining rhythm?',
        createdAt: DateTime.now().subtract(
          const Duration(days: 3, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '39',
        dynamicId: '7',
        userId: '6',
        content:
            'Great video quality! The camera work really captures the intensity of the training session.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 3, minutes: 15),
        ),
      ),

      // 动态8的评论 - "Urban running adventure!" (5条评论)
      ContentCommentModel(
        id: '40',
        dynamicId: '8',
        userId: '1',
        content:
            'That hidden park discovery was so cool! I love how running can lead to unexpected adventures.',
        createdAt: DateTime.now().subtract(const Duration(days: 4, hours: 2)),
      ),
      ContentCommentModel(
        id: '41',
        dynamicId: '8',
        userId: '2',
        content:
            'Urban running is such a unique experience! The energy of the city really comes through in your video.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 4, hours: 1, minutes: 30),
        ),
      ),
      ContentCommentModel(
        id: '42',
        dynamicId: '8',
        userId: '3',
        content:
            'I love exploring new routes in the city! Every run becomes an adventure when you\'re open to discovery.',
        createdAt: DateTime.now().subtract(const Duration(days: 4, hours: 1)),
      ),
      ContentCommentModel(
        id: '43',
        dynamicId: '8',
        userId: '4',
        content:
            'The city lights and architecture make for such a dynamic running backdrop! Great cinematography.',
        createdAt: DateTime.now().subtract(
          const Duration(days: 4, minutes: 45),
        ),
      ),
      ContentCommentModel(
        id: '44',
        dynamicId: '8',
        userId: '5',
        content:
            'Running through different neighborhoods gives you such a unique perspective of the city!',
        createdAt: DateTime.now().subtract(
          const Duration(days: 4, minutes: 30),
        ),
      ),
    ];
  }

  /// 初始化默认点赞数据
  void _populateDefaultLikes() {
    _likes.clear();
    _likes.addAll(_generateDefaultLikes());
  }

  /// 获取默认点赞数据
  List<ContentLikeModel> _generateDefaultLikes() {
    return [
      // 动态1的点赞
      ContentLikeModel(
        id: '1',
        dynamicId: '1',
        userId: '2',
        createdAt: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 45),
        ),
      ),
      ContentLikeModel(
        id: '2',
        dynamicId: '1',
        userId: '3',
        createdAt: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 20),
        ),
      ),
      ContentLikeModel(
        id: '3',
        dynamicId: '1',
        userId: '4',
        createdAt: DateTime.now().subtract(const Duration(hours: 1)),
      ),

      // 动态2的点赞
      ContentLikeModel(
        id: '4',
        dynamicId: '2',
        userId: '1',
        createdAt: DateTime.now().subtract(
          const Duration(hours: 4, minutes: 30),
        ),
      ),
      ContentLikeModel(
        id: '5',
        dynamicId: '2',
        userId: '5',
        createdAt: DateTime.now().subtract(const Duration(hours: 4)),
      ),

      // 动态7的点赞（视频动态）
      ContentLikeModel(
        id: '6',
        dynamicId: '7',
        userId: '1',
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 15)),
      ),
      ContentLikeModel(
        id: '7',
        dynamicId: '7',
        userId: '3',
        createdAt: DateTime.now().subtract(const Duration(days: 2, hours: 10)),
      ),

      // 动态8的点赞（视频动态）
      ContentLikeModel(
        id: '8',
        dynamicId: '8',
        userId: '2',
        createdAt: DateTime.now().subtract(const Duration(days: 3, hours: 8)),
      ),
      ContentLikeModel(
        id: '9',
        dynamicId: '8',
        userId: '4',
        createdAt: DateTime.now().subtract(const Duration(days: 3, hours: 4)),
      ),
    ];
  }

  /// 发布动态
  Future<bool> broadcastContent({
    required String userId,
    required String title,
    required String content,
    required ContentType type,
    String? imagePath,
    String? videoPath,
    String? coverImagePath,
  }) async {
    setBusy(true);
    try {
      if (title.trim().isEmpty) {
        setError('Title cannot be empty');
        return false;
      }

      if (content.trim().isEmpty) {
        setError('Content cannot be empty');
        return false;
      }

      if (type == ContentType.image && imagePath == null) {
        setError('Image content requires image path');
        return false;
      }

      if (type == ContentType.video &&
          (videoPath == null || coverImagePath == null)) {
        setError('Video content requires video path and cover image path');
        return false;
      }

      // 创建动态记录
      final dynamic = ContentModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        userId: userId,
        title: title.trim(),
        content: content.trim(),
        type: type,
        imagePath: imagePath,
        videoPath: videoPath,
        coverImagePath: coverImagePath,
        createdAt: DateTime.now(),
      );

      _dynamics.insert(0, dynamic); // 插入到列表开头
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 添加动态评论
  Future<bool> appendComment({
    required String dynamicId,
    required String userId,
    required String content,
  }) async {
    setBusy(true);
    try {
      if (content.trim().isEmpty) {
        setError('Comment content cannot be empty');
        return false;
      }

      // 验证动态存在
      _dynamics.firstWhere(
        (d) => d.id == dynamicId,
        orElse: () => throw Exception('Content not found'),
      );

      // 创建评论记录
      final comment = ContentCommentModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        dynamicId: dynamicId,
        userId: userId,
        content: content.trim(),
        createdAt: DateTime.now(),
      );

      _comments.add(comment);

      // 更新动态的评论数
      final dynamicIndex = _dynamics.indexWhere((d) => d.id == dynamicId);
      if (dynamicIndex != -1) {
        _dynamics[dynamicIndex] = _dynamics[dynamicIndex].copyWith(
          commentCount: _dynamics[dynamicIndex].commentCount + 1,
        );
      }

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 点赞/取消点赞动态
  Future<bool> toggleAppreciation({
    required String dynamicId,
    required String userId,
  }) async {
    setBusy(true);
    try {
      // 检查是否已经点赞
      final existingLikeIndex = _likes.indexWhere(
        (like) => like.dynamicId == dynamicId && like.userId == userId,
      );

      final dynamicIndex = _dynamics.indexWhere((d) => d.id == dynamicId);
      if (dynamicIndex == -1) {
        setError('Content not found');
        return false;
      }

      if (existingLikeIndex != -1) {
        // 取消点赞
        _likes.removeAt(existingLikeIndex);
        _dynamics[dynamicIndex] = _dynamics[dynamicIndex].copyWith(
          likeCount: _dynamics[dynamicIndex].likeCount - 1,
        );
      } else {
        // 添加点赞
        final like = ContentLikeModel(
          id: DateTime.now().millisecondsSinceEpoch.toString(),
          dynamicId: dynamicId,
          userId: userId,
          createdAt: DateTime.now(),
        );
        _likes.add(like);
        _dynamics[dynamicIndex] = _dynamics[dynamicIndex].copyWith(
          likeCount: _dynamics[dynamicIndex].likeCount + 1,
        );
      }

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 检查用户是否已点赞某个动态
  bool hasUserAppreciated(String dynamicId, String userId) {
    return _likes.any(
      (like) => like.dynamicId == dynamicId && like.userId == userId,
    );
  }

  /// 获取动态的所有评论
  List<ContentCommentModel> retrieveComments(String dynamicId) {
    return _comments.where((comment) => comment.dynamicId == dynamicId).toList()
      ..sort((a, b) => a.createdAt.compareTo(b.createdAt));
  }

  /// 获取用户的动态
  List<ContentModel> fetchUserContent(String userId) {
    return _dynamics.where((dynamic) => dynamic.userId == userId).toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 获取用户点赞的动态
  List<ContentModel> fetchUserLikedDynamics(String userId) {
    // 获取用户点赞的动态ID列表
    final likedDynamicIds =
        _likes
            .where((like) => like.userId == userId)
            .map((like) => like.dynamicId)
            .toList();

    // 根据ID获取动态对象
    return _dynamics
        .where((dynamic) => likedDynamicIds.contains(dynamic.id))
        .toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 获取用户的总点赞数
  int getUserTotalLikes(String userId) {
    return _dynamics
        .where((dynamic) => dynamic.userId == userId)
        .fold(0, (total, dynamic) => total + dynamic.likeCount);
  }

  /// 根据ID获取动态
  ContentModel? locateContent(String dynamicId) {
    try {
      return _dynamics.firstWhere((dynamic) => dynamic.id == dynamicId);
    } catch (e) {
      return null;
    }
  }

  /// 删除动态
  Future<bool> removeContent(String dynamicId) async {
    setBusy(true);
    try {
      final dynamicIndex = _dynamics.indexWhere((d) => d.id == dynamicId);

      if (dynamicIndex == -1) {
        setError('Content not found or you do not have permission to delete');
        return false;
      }

      // 删除动态
      _dynamics.removeAt(dynamicIndex);

      // 删除相关评论
      _comments.removeWhere((comment) => comment.dynamicId == dynamicId);

      // 删除相关点赞
      _likes.removeWhere((like) => like.dynamicId == dynamicId);

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 删除评论
  Future<bool> removeComment(String commentId) async {
    setBusy(true);
    try {
      final commentIndex = _comments.indexWhere((c) => c.id == commentId);

      if (commentIndex == -1) {
        setError('Comment not found');
        return false;
      }

      // 删除评论
      _comments.removeAt(commentIndex);

      // 更新动态的评论数量
      final comment = _comments.firstWhere((c) => c.id == commentId);
      final dynamicIndex = _dynamics.indexWhere(
        (d) => d.id == comment.dynamicId,
      );
      if (dynamicIndex != -1) {
        _dynamics[dynamicIndex] = _dynamics[dynamicIndex].copyWith(
          commentCount: _dynamics[dynamicIndex].commentCount - 1,
        );
      }

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 搜索动态
  List<ContentModel> exploreContent(String keyword) {
    if (keyword.isEmpty) return dynamics;

    return _dynamics.where((dynamic) {
      return dynamic.content.toLowerCase().contains(keyword.toLowerCase());
    }).toList();
  }
}
